<template>
	<base-page title="添加多商户券" backgroundColor="white">
		<view class="p-16">
			<view class="flex item-center">
				<text class="text-black text-bold">券名称</text>
				<text class="ml-4 text-color-hint">{{activeGoods.goodsName && activeGoods.goodsName.trim().length || 0}}/30</text>
			</view>
			<view class="mt-8 radius-8 bg-default px-16 py-12">
				<input v-model="activeGoods.goodsName" class="h-20 fs-14" :maxlength="30" placeholder-class="text-color-hint" placeholder="例:  50元无门槛多店通用餐饮券" />
			</view>
			<view class="flex item-center flex-wrap mt-20">
				<view class="text-black text-bold">券价格</view>
				<view class="fs-12 text-color-hint">
					券价格即为订单核销后需要结算给商户的金额，若策划人自己做活动，券价格建议0元，无需向商户分账，活动收入全部归属于策划人
				</view>
			</view>
			<view class="mt-8 radius-8 bg-default px-16 py-12">
				<input v-model="activeGoods.goodsPrice" type="digit" class="h-20 fs-14" placeholder-class="text-color-hint" placeholder="请输入价格" />
			</view>
			<view class="flex item-center mt-20">
				<text class="text-black text-bold">使用说明</text>
			</view>
			<view class="mt-8 radius-8 bg-default px-16 py-12">
				<textarea v-model="activeGoods.details" class="fs-14" style="min-height:20px;" :maxlength="-1" :auto-height="true" placeholder-class="text-color-hint" placeholder="*请输入使用说明" />
			</view>
			<view class="mt-20 flex justify-between item-center">
				<text class="text-black text-bold">商品数量</text>
				<number-input-box :value="activeGoods.goodsNum" :min="1" @change="activeGoods.goodsNum = $event"></number-input-box>
			</view>
		</view>
		<view class="h-1 w-full bg-default my-20"></view>
		<view>
			<view class="mt-16 mx-16 mb-8 flex-shrink">
				<text class="fs-16">请选择活动商户</text>
			</view>
			<view class="search-bar mx-16 mb-12 flex-shrink" @click="toSearch">
				<image class="w-20 h-20 mr-5" src="@/static/svg/icon-search.svg"></image>
				<text class="fs-12 text-color-hint">搜商户</text>
			</view>
			<view class="flex-1 flex">
				<scroll-view ref="navScrollView" class="left-nav flex-shrink h-full" scroll-y style="max-height:calc(100vh - 150px);">
					<view class="left-nav-item" :class="currentNav===0?'active':''" @click="onNavItemClick(null, 0)">
						<uni-badge :text="selectedList.length" size="small" :offset="[-6,0]" absolute="rightTop" :customStyle="{background: '#FA4543'}">
							<text>已选</text>
						</uni-badge>
					</view>
					<view v-for="(item, i) in merchantTypeList" :key="i+1" class="left-nav-item" :class="currentNav===i+1?'active':''" @click="onNavItemClick(item, i+1)">
						<uni-badge :text="selectedMerchantGoodsNum(item)" size="small" :offset="[-6,0]" absolute="rightTop" :customStyle="{background: '#FA4543'}">
							<text>{{item.mccName}}</text>
						</uni-badge>
					</view>
				</scroll-view>
				<view class="flex-1 ml-16">
					<scroll-view scroll-y="true">
						<template v-if="currentNav===0">
							<view v-for="(item,i) in selectedList" :key="i" class="mr-16 mb-16">
								<view class="flex">
									<view class="flex">
										<view class="flex item-center">
											<image class="w-16 h-16 mr-4" src="@/static/svg/activity/icon-radio-delete.svg" @click="deleteSelected(item)"></image>
											<image class="goods-img" :src="item.avatar"></image>
										</view>
									</view>
									<view class="mb-6">
										<view class="mb-4"><text class="goods-name">{{item.merchantShortName}}</text></view>
									</view>
								</view>
							</view>
						</template>
						<template v-else>
							<view v-for="(item,i) in merchantList" :key="i" class="mr-16 mb-16">
								<view class="flex">
									<view class="flex">
										<view class="flex item-center">
											<image v-if="hasChecked(item)" class="w-16 h-16 mr-4" src="@/static/svg/activity/icon-radio-check-blue.svg" @click="noCheck(item)"></image>
											<image v-else class="w-16 h-16 mr-4" src="@/static/svg/activity/icon-radio-default.svg" @click="check(item)"></image>
											<image class="goods-img" :src="item.avatar"></image>
										</view>
									</view>
									<view class="mb-6">
										<view class="mb-4"><text class="goods-name">{{item.merchantShortName}}</text></view>
									</view>
								</view>
							</view>
						</template>
					</scroll-view>
				</view>
			</view>
		</view>
		<template #footer>
			<view class="m-12 flex">
				<button class="flex-1 flex center radius-8 h-46 fs-16 uni-bg-white text-color-hint mr-12" style="border:1px solid rgba(51, 51, 51, 0.60);" @click="goBack">取消</button>
				<button class="flex-1 flex center radius-8 h-46 fs-16 bg-primary text-white" @click="submit">确认</button>
			</view>
		</template>
	</base-page>
</template>

<script setup name="AddMerchantCoupon">
	/**
	 * 添加多商户券
	 */
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import {
		computed,
		onMounted,
		ref,
		unref,
		getCurrentInstance,
	} from 'vue'
	import { getRelationMerchantApi } from '@/api/activity.js'
	import { getMerchantTypeApi } from '@/api/common.js'
	import { getActiveLimitApi } from '@/api/business.js'
	import { usePublishStore } from '@/stores/modules/publish.js'
	
	const publishStore = usePublishStore()
	
	const instance = getCurrentInstance()
	
	const goBack = () => uni.navigateBack()
	
	const currentNav = ref(0)
	const selectedList = ref([])
	
	const navScrollView = ref(null)
	const navScrollIntoView = ref('')
	const contentScrollView = ref(null)
	const contentScrollIntoView = ref('')
	
	const activeGoods = ref({
		goodsName: '',
		goodsPrice: '',
		details: '',
		goodsNum: 1,
		goodsId: '',
		merchantId: 0,
		mulState: 2,
	})
	
	let singleActiveMerchantCount = 0
	
	const getActiveCount = () => {
		getActiveLimitApi().then(res => {
			singleActiveMerchantCount = res.singleActiveMerchantCount
		})
	}
	
	const toSearch = () => {
		uni.navigateTo({
			url: '/pagesG/publish/search-merchant',
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					selectedList: unref(selectedList)
				})
			},
			events: {
				onGoodsSelect: (list) => {
					console.log('搜索页添加的', list, selectedList.value)
					list.forEach(it => {
						if (!selectedList.value.some(el => el.id === it.id)) {
							selectedList.value.push({...it})
						}
					})
				}
			}
		})
	}
	
	const onNavItemClick = (item, index) => {
		if (currentNav.value !== index) {
			currentNav.value = index
			if (index !== 0) {
				queryParams.value.mccCode = item.mccCode
				queryParams.value.pageNum = 1
				getRelationMerchant()
			}
		}
	}
	
	// 勾选
	const check = (item) => {
		const obj = selectedList.value.find(it => it.id === item.id)
		let currentIds = []
		selectedList.value.forEach(item => {
			currentIds.push(item.id)
		})
		let ids = [...new Set([...publishStore.merchantIds, ...currentIds])]
		if (!obj) {
			if(singleActiveMerchantCount && singleActiveMerchantCount <= ids.length && !ids.includes(item.id)){
				uni.showToast({
					icon: 'none',
					title: `活动仅限${singleActiveMerchantCount}个商户参与`
				})
				return
			}
			item.goodsNum = 1
			selectedList.value.push(item)
		}
	}
	
	// 取消勾选
	const noCheck = (item) => {
		selectedList.value = selectedList.value.filter(it => it.id !== item.id)
		item.goodsNum = 0
	}
	
	// 删除已选
	const deleteSelected = (item) => {
		selectedList.value = selectedList.value.filter(it => it.id !== item.id)
	}
	
	// 是否添加过
	const hasChecked = (item) => {
		return selectedList.value.some(it => it.id === item.id)
	}
	
	const onSelectChange = (item, val) => {
		const obj = selectedList.value.find(it => it.id === item.id)
		if (obj) {
			obj.goodsNum = val
		}
		item.goodsNum = val
	}
	
	// 商户类型中，选中的商户数
	const selectedMerchantGoodsNum = (item) => {
		return selectedList.value.reduce((pre, cur) => {
			return pre + (cur.mcc == item.mccCode ? 1 : 0 )
		}, 0)
	}
	
	const submit = () => {
		console.log('校验', activeGoods.value, selectedList.value)
		if (!activeGoods.value.goodsName || activeGoods.value.goodsName.trim().length === 0) {
			showToast('请输入券名称')
			return
		}
		if (!activeGoods.value.goodsPrice) {
			showToast('请输入券价格')
			return
		}
		if (!activeGoods.value.details) {
			showToast('请输入使用说明')
			return
		}
		if (activeGoods.value.goodsNum <= 0) {
			showToast('请输入商品数量')
			return
		}
		if (selectedList.value.length) {
			activeGoods.value.merchantName = `适用${selectedList.value.length}家`
			activeGoods.value.goodsId = selectedList.value.map(it => it.id).join(',')
			activeGoods.value.merchantIds = selectedList.value.map(it => it.id)
			const eventChannel = instance.ctx.getOpenerEventChannel()
			eventChannel.emit('onMerchantCouponAdd', {
				merchantCoupon: unref(activeGoods),
			})
			uni.navigateBack()
		} else {
			showToast('请选择活动商户')
		}
	}
	
	const showToast = (title) => {
		uni.showToast({
			title,
			icon: 'none'
		})
	}
	
	// 商户类型
	const merchantTypeList = ref([])
	const getMerchantType = () => {
		getMerchantTypeApi().then(res => {
			const list = res || []
			merchantTypeList.value = list
			if (list.length) {
				currentNav.value = 1
				queryParams.value.mccCode = list[0].mccCode
				getRelationMerchant()
			}
		})
	}
	
	// 商户列表
	const queryParams = ref({
		mccCode: '',
		merchantName: '',
		pageNum: 1,
		pageSize: 5000,
	})
	const merchantList = ref([])
	const getRelationMerchant = () => {
		getRelationMerchantApi(unref(queryParams)).then(res => {
			const list = res.list || []
			merchantList.value = list
		})
	}
	
	onShow(() => {
		getActiveCount()
	})

	onLoad(()=>{
		const eventChannel = instance.ctx.getOpenerEventChannel();
		eventChannel.on('presetMerchantCoupon', function(data) {
			activeGoods.value.goodsName = data.data.goodsName;
			activeGoods.value.goodsPrice = data.data.goodsPrice;
			activeGoods.value.details = data.data.details;
			activeGoods.value.goodsNum = Number(data.data.goodsNum);
			selectedList.value = data.data.merchantIds.map(id=>({id}));
		})
	})
	
	onMounted(() => {
		getMerchantType()
	})
</script>

<style lang="scss" scoped>
	.search-bar {
		display: flex;
		height: 38px;
		padding: 0 16px;
		align-items: center;
		flex-shrink: 0;
		border-radius: 8px;
		background: #F5F5F5;
	}
	.left-nav {
		width: 80px;
		
		.left-nav-item {
			display: flex;
			padding: 10px 12px;
			align-items: center;
			background: #F2F2F2;
			color: #666;
			font-size: 12px;
			font-weight: 400;
			line-height: 22px;
			
			&.active {
				color: #333333;
				border-radius: 0px 8px 8px 0px;
				background-color: #FFF;
			}
		}
	}
	.goods-img {
		width: 64px;
		height: 64px;
		border-radius: 12px;
		margin-right: 12px;
	}
	.goods-name {
		color: #333;
		font-family: PingFang SC;
		font-size: 14px;
		font-style: normal;
		font-weight: 600;
		line-height: normal;
	}
	.goods-price {
		color: #FA4543;
		font-size: 14px;
		font-style: normal;
		font-weight: 600;
		line-height: normal;
		
		.symbol {
			font-size: 11px;
			font-weight: 600;
		}
	}
	.goods-stock {
		color: rgba(51, 51, 51, 0.60);
		font-family: PingFang SC;
		font-size: 10px;
		font-style: normal;
		font-weight: 400;
		line-height: normal;
	}
</style>
